package 二叉树;


/**
 * https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493352&idx=1&sn=608eb4d53e040c86ba41a1b7ec4d257d&chksm=9bd418e0aca391f6ac5f11ce7da53e55f20d88cb7dc5d5fa90b63a8b6d0e6d70af56db735d9b&scene=178&cur_album_id=2165089327943417857#rd
 */
public class _105_从前序与中序遍历序列构造二叉树 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private TreeNode buildTree(int[] preorder, int pStart,int pEnd,int[] inorder,int iStart,int iEnd) {
        if(pStart > pEnd || iStart > iEnd) return null;

        int rootValue = preorder[pStart];
        TreeNode root = new TreeNode(rootValue);

        // 这边遍历不是从istart到iend了
        int index = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (rootValue == inorder[i]) {
                index = i;
                break;
            }
        }

        root.left = buildTree(preorder,pStart+1,pStart + (index - iStart) ,inorder,iStart,index-1);
        root.right = buildTree(preorder,pStart+1+(index-iStart),pEnd,inorder,index+1,iEnd);

        return root;
    }
}
